﻿<template>
  <div v-if = 'showMDJson'>
    <link rel="stylesheet" href = "/static/editorMd/css/editormd.min.css">
    <link rel="stylesheet" href = "/static/editorMd/examples/css/style.css" />
    <div id = 'editorId_JSON'>
      <textarea style="display:none;"></textarea>
    </div>
  </div>
</template>

<script>
import scriptjs from 'scriptjs'
export default {
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    // 默认值
    defaultValue: {
      type: String
    },
    // 初始化的状态
    showMDJson: {
      type: Boolean
    }
  },
  data () {
    return {
      currentValue: this.defaultValue || null,
      editorJson: null,
      defaultConfig: {
        width: '100%',
        height: 600,
        watch: false,
        toolbar: false,
        codeFold: true,
        searchReplace: true,
        readOnly: false, // 只读模式
        placeholder: '请输入正确的JSON结构...',
        markdown: '',
        theme: 'default',
        editorTheme: 'default',
        mode: 'text/json',
        path: '/static/editorMd/lib/'
      }
    }
  },
  mounted () {
    this.init_page()
  },
  watch: {
    showMDJson: {
      deep: true,
      handler (val) {
        if (val) {
          this.init_page()
        } else {
          this.editorJson = null
        }
      }
    }
  },
  methods: {
    fetchScript: function (url) {
      return new Promise((resolve) => {
        scriptjs(url, () => {
          resolve()
        })
      })
    },
    // 获取值
    getMdValue () {
      let val = this.editorJson.getMarkdown()
      if (!val) {
        this.$emit('update:defaultValue', '')
      } else {
        try {
          console.log(JSON.parse(val))
          this.$emit('update:defaultValue', encodeURIComponent(val))
        } catch (err) {
          this.$message({
            message: '请检查您输入的JSON格式是否正确',
            type: 'warning',
            duration: '2000'
          })
          this.$emit('update:defaultValue', 'JsonError')
        }
      }
    },
    // 初始化页面的方法
    init_page () {
      let _self = this
      _self.editorJson = null
      _self.currentValue = _self.defaultValue ? decodeURIComponent(_self.defaultValue) : ''
      // 根据浏览器的高度来设置编辑器的高度
      if (window.screen.height > 800) {
        _self.defaultConfig.height = 660
      } else {
        _self.defaultConfig.height = 400
      }
      _self.defaultConfig.readOnly = _self.disabled
      _self.defaultConfig.markdown = _self.currentValue
      _self.initEditor()
    },
    // 初始化编辑器
    initEditor: async function () {
      let _self = this
      await this.fetchScript('/static/editorMd/js/jquery.min.js')
      await this.fetchScript('/static/editorMd/editormd.min.js')
      _self.$nextTick(() => {
        _self.editorJson = window.editormd('editorId_JSON', _self.defaultConfig)
      })
    }
  }
}
</script>
